﻿using HomeCareLibrary.Constants;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HomeCareLibrary.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class HybridAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            var userIdSession = HttpContext.Current.Session[SessionConstants.USER_ID];

            // Check for POST Data, if found and having the login details, then dont perform MVC authorize part.
            var userIdPosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.USER_ID);
            var modePosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.MODE);
            int userId = 0;

            // If user id POST data exists and is valid user id and also mode is from mobile, skip authorization.
            if (userIdPosted != null && int.TryParse(userIdPosted.AttemptedValue, out userId) && (modePosted.AttemptedValue == ApplicationModeConstants.IPHONE_APP || modePosted.AttemptedValue == ApplicationModeConstants.ANDROID_APP))
            {
                return;
            }
            else if (userIdSession != null)
            {
                return;
            }


            base.OnAuthorization(filterContext);
        }
    }
}